let viewMode = 0; // 0 chart 1 table
let currentDate = dayjs().format('YYYY-MM-DD');
let dataList = []
let chart;
let cardRendered = false;

const BORDER_COLORS = [
    'rgb(54, 162, 235)',
    'rgb(255, 99, 132)',
    'rgb(255, 159, 64)',
    'rgb(255, 205, 86)',
    'rgb(75, 192, 192)',
    'rgb(153, 102, 255)',
    'rgb(201, 203, 207)' // grey
];
const BACKGROUND_COLORS = BORDER_COLORS.map((color) => color.replace('rgb(', 'rgba(').replace(')', ', 0.5)'));

layui.use(['laydate'], function () {
    let laydate = layui.laydate;
    laydate.render({
        elem: '#date',
        type: 'date',
        max: 0,
        min: -30,
        value: currentDate,
        done: function (value, date, endDate) {
            $('#beginTime').val(value + ' 00:00:00');
            $('#endTime').val(value + ' 23:59:59');
        }
    })
})
$('#beginTime').val(currentDate + ' 00:00:00');
$('#endTime').val(currentDate + ' 23:59:59');

function changeView() {
    if (viewMode) {
        $('#table-row').hide()
        $('#chart-row').show();
        $('#view-btn>i').attr('class', 'fa fa-list');
        viewMode = 0;
        $('#download-btn').hide();
    } else {
        $('#chart-row').hide()
        $('#table-row').show();
        $('#view-btn>i').attr('class', 'fa fa-line-chart');
        viewMode = 1;
        $('#download-btn').show();
    }
}

function openDownloadDialog() {
    let content = `
            <form class="layui-form" style="padding: 50px 20px">
              <div class="layui-form-item">
                <label class="layui-form-label">下载类型：</label>
                 <div class="layui-input-block">
                    <select name="download-type" lay-filter="type" id="download-type">
                        <option value="0">按月下载</option>
                        <option value="1">按年下载</option>
                      </select>
                 </div>
              </div>
              <div class="layui-form-item layui-form-text">
                <label class="layui-form-label">日期选择：</label>
                <div class="layui-input-block">
                   <input type="text" autocomplete="off" class="layui-input" id="download-value">
                </div>
              </div>
          </form>
            `

    layer.open({
        type: 1,
        area: ['350px', '320px'],
        fix: false, // 不固定
        maxmin: false,
        shade: 0.3,
        title: '下载',
        content: content,
        btn: ['确定', '关闭'],
        // 弹层外区域关闭
        shadeClose: true,
        yes: function () {
            let dateStr = $('#download-value').val(), beginTime, endTime, type;
            if (dateStr.includes("-")) {
                beginTime = dateStr + '-01 00:00:00';
                endTime = dayjs(dateStr, 'YYYY-MM').add(1, 'M').subtract(1, 's').format("YYYY-MM-DD HH:mm:ss");
            } else {
                beginTime = dateStr + '-01-01 00:00:00';
                endTime = dateStr + '-12-31 23:59:59';
            }
            download(beginTime, endTime)
        },
        cancel: function () {
            return true;
        },
        success: function () {

            layui.form.render();
            layui.laydate.render({
                elem: '#download-value',
                type: 'month',
                value: dayjs().format('YYYY-MM'),
                max: 0,
            })

            layui.form.on('select(type)', function (data) {
                var selectedValue = parseInt(data.value);
                layui.laydate.render({
                    elem: '#download-value',
                    type: selectedValue ? 'year' : 'month',
                    value: dayjs().format(selectedValue ? 'YYYY' : 'YYYY-MM'),
                    max: 0,
                })
            })
        }
    });
}

function download(beginTime, endTime) {
    var index = layer.load(1);
    var dataParam = [];
    dataParam.push({"name": "params[beginTime]", "value": beginTime});
    dataParam.push({"name": "params[endTime]", "value": endTime});
    dataParam.push({"name": "boatCode", "value": boatCode});

    $.post(downloadUrl, dataParam, function (result) {
        layer.close(index);
        if (result.code === web_status.SUCCESS) {
            var url = "/common/download?fileName=" + encodeURI(result.msg) + "&delete=" + true
            window.location.href = url;
            // window.open(url)
        } else {
            $.modal.alertError(result.msg);
        }
    });
}

function search() {
    currentDate = $('#date').val();
    $.table.search();
}

function resetInput() {
    currentDate = dayjs().format('YYYY-MM-DD');
    $('#date').val(currentDate);
    $('#beginTime').val(currentDate + ' 00:00:00');
    $('#endTime').val(currentDate + ' 23:59:59');
    $.table.search();
}

function setColHeight() {
    $('.col-sm-6').height($('.col-sm-6').width() * 600 / 1150);
    $('#chart-row').height($('#chart-row').width() * 600 / 1150);

    var cardHeight4 = $('.col-sm-4').width() * 3 / 5;
    if (cardHeight4 < 180) cardHeight4 = 180;
    if (cardHeight4 > 200) cardHeight4 = 200;
    $('.col-sm-4').height(cardHeight4);

    var cardHeight3 = $('.col-sm-3').width() * 3 / 5;
    if (cardHeight3 < 180) cardHeight3 = 180;
    if (cardHeight3 > 200) cardHeight3 = 200;
    $('.col-sm-3').height(cardHeight3);

}

window.addEventListener('resize', () => {
    setColHeight();
    windowResizeCallback();
});


Chart.defaults.backgroundColor = '#9BD0F5';
Chart.defaults.borderColor = 'rgba(255,255,255,0.3)';
Chart.defaults.color = 'rgba(255,255,255,0.9)';

function initChart() {
    if (chart) {
        chart.update();
    } else {
        chart = new Chart(document.getElementById('chart'), config);
    }
}

function clearData() {
    chartData.labels = [];
    for (let i = 0; i < chartData.datasets.length; i++) {
        chartData.datasets[i].data = [];
    }
}

setColHeight();
